// miniprogram/pages/signUpRecord/signUpRecord.js

import Encoder from "../../utils/Encoder";
import Decoder from "../../utils/Decoder";
//实现参考例子
// var message = "减肥是一件困难的事情";

// //UTF-8转GBK
// var gbkArray = Encoder.hexstrToArray(Encoder.stringToGbkHexstr(message));
// console.log("gbkArray>>" + gbkArray);
// //GBK转UTF-8
// var utfStr = Decoder.GBKHexstrToString(Decoder.binaryarrayToHexstr(gbkArray));
// console.log("utfStr>>" + utfStr);

Page({

  /**
   * 页面的初始数据
   */
  data: {
    signUpList: [],
    batchIds: [], // 选中的ID
    select_all: false,
    select_anti: false,
    gameId: "",
    gameTitle: "",

    select_unknown: false,
    select_success: false,
    select_fail: false,
    current_state: "",
  },

  //全选
  selectAll: function () {
    var that = this;
    var arr = [];   //存放选中id的数组
    for (let i = 0; i < that.data.signUpList.length; i++) {
      that.data.signUpList[i].checked = (!that.data.select_all)
      arr.push(that.data.signUpList[i]._id)
    }
    // console.log(arr)
    that.setData({
      signUpList: that.data.signUpList, // 保证更新
      select_all: (!that.data.select_all),
      batchIds: arr
    })
  },

  // 反选
  selectAnti: function () {
    var that = this;
    var arr = [];   //存放选中id的数组
    for (let i = 0; i < that.data.signUpList.length; i++) {
      that.data.signUpList[i].checked = (!that.data.signUpList[i].checked)
      if (that.data.signUpList[i].checked == true) {
        // 全选获取选中的值
        arr.push(that.data.signUpList[i]._id)
      }
    }
    // console.log(arr)
    that.setData({
      signUpList: that.data.signUpList, // 保证更新
      batchIds: arr
    })

    // 修改全选框
    if (that.data.signUpList.length != that.data.batchIds.length) {
      that.setData({
        select_all: false
      })
    } else {
      that.setData({
        select_all: true
      })
    }
  },

  // 单选
  checkboxChange: function (e) {
    this.setData({
      batchIds: e.detail.value  //单个选中的值
    })
  },

  // 只看未知
  checkUnknown: function (e) {
    let that = this
    if(that.data.select_unknown == false) {
      that.setData({
        select_unknown: true,
        select_all: false,
        select_anti: false,
        select_success: false,
        select_fail: false,
        current_state: "未知"
      })
      that.onReady()
    } else {
      if (that.data.select_success == false && that.data.select_fail == false) {
        that.setData({
          select_unknown: false,
          select_all: false,
          select_anti: false,
          select_success: false,
          select_fail: false,
          current_state: ""
        })
        that.onReady()
      }
    }
  },

  // 只看成功
  checkSuccess: function (e) {
    let that = this
    if (that.data.select_success == false) {
      that.setData({
        select_unknown: false,
        select_all: false,
        select_anti: false,
        select_success: true,
        select_fail: false,
        current_state: "成功"
      })
      that.onReady()
    } else {
      if (that.data.select_unknown == false && that.data.select_fail == false) {
        that.setData({
          select_unknown: false,
          select_all: false,
          select_anti: false,
          select_success: false,
          select_fail: false,
          current_state: ""
        })
        that.onReady()
      }
    }
  },

  // 只看失败
  checkFail: function (e) {
    let that = this
    if (that.data.select_fail == false) {
      that.setData({
        select_unknown: false,
        select_all: false,
        select_anti: false,
        select_success: false,
        select_fail: true,
        current_state: "失败"
      })
      that.onReady()
    } else {
      if (that.data.select_unknown == false && that.data.select_success == false) {
        that.setData({
          select_unknown: false,
          select_all: false,
          select_anti: false,
          select_success: false,
          select_fail: false,
          current_state: ""
        })
        that.onReady()
      }
    }
  },

  // 修改单选的checked
  setChecked: function (e) {
    // console.log(e)
    let that = this
    for (let i = 0; i < that.data.signUpList.length; i++) {
      if (that.data.signUpList[i]._id == e.currentTarget.dataset.id) {
        that.data.signUpList[i].checked = (!that.data.signUpList[i].checked)
        if (that.data.signUpList[i].checked == false) {
          that.setData({
            select_all: false
          })
        }
        break;
      } 
    }

    if (that.data.signUpList.length != that.data.batchIds.length) {
      that.setData({
        select_all: false
      })
    } else {
      that.setData({
        select_all: true
      })
    }
  },

  // 点击状态、组别、姓名、城市、学校、导师、考号等按对应属性排序
  // 状态排序-begin
  orderByState: function(e) {
    console.log("根据状态排序")
    var arr = this.data.signUpList;
    this.setData({
      signUpList: arr.sort(this.compState)
    }) 
  },

  compState: function (a, b) {
    if (Encoder.hexstrToArray(Encoder.stringToGbkHexstr(a.state)) >= Encoder.hexstrToArray(Encoder.stringToGbkHexstr(b.state)))
      return 1
    else
      return -1
  },
  // 状态排序-end

  // 组别排序-begin
  orderByGroup: function (e) {
    console.log("根据组别排序")
    var arr = this.data.signUpList;
    this.setData({
      signUpList: arr.sort(this.compGroup)
    })
  },

  compGroup: function (a, b) {
    if (Encoder.hexstrToArray(Encoder.stringToGbkHexstr(a.group)) >= Encoder.hexstrToArray(Encoder.stringToGbkHexstr(b.group)))
      return 1
    else
      return -1
  },
  // 组别排序-end

  // 姓名排序-begin
  orderByName: function (e) {
    console.log("根据姓名排序")
    var arr = this.data.signUpList;
    this.setData({
      signUpList: arr.sort(this.compName)
    })
  },

  compName: function (a, b) {
    if (Encoder.hexstrToArray(Encoder.stringToGbkHexstr(a.user.name)) >= Encoder.hexstrToArray(Encoder.stringToGbkHexstr(b.user.name)))
      return 1
    else
      return -1
  },
  // 姓名排序-end

  // 城市排序-begin
  orderByCity: function (e) {
    console.log("根据城市排序")
    var arr = this.data.signUpList;
    this.setData({
      signUpList: arr.sort(this.compCity)
    })
  },

  compCity: function (a, b) {
    if (Encoder.hexstrToArray(Encoder.stringToGbkHexstr(a.user.city)) >= Encoder.hexstrToArray(Encoder.stringToGbkHexstr(b.user.city)))
      return 1
    else
      return -1
  },
  // 城市排序-end

  // 学校排序-begin
  orderBySchool: function (e) {
    console.log("根据学校排序")
    var arr = this.data.signUpList;
    this.setData({
      signUpList: arr.sort(this.compSchool)
    })
  },

  compSchool: function (a, b) {
    if (Encoder.hexstrToArray(Encoder.stringToGbkHexstr(a.user.school)) >= Encoder.hexstrToArray(Encoder.stringToGbkHexstr(b.user.school)))
      return 1
    else
      return -1
  },
  // 学校排序-end

  // 导师排序-begin
  orderByTutor: function (e) {
    console.log("根据导师排序")
    var arr = this.data.signUpList;
    this.setData({
      signUpList: arr.sort(this.compTutor)
    })
  },

  compTutor: function (a, b) {
    if (Encoder.hexstrToArray(Encoder.stringToGbkHexstr(a.tutor)) >= Encoder.hexstrToArray(Encoder.stringToGbkHexstr(b.tutor)))
      return 1
    else
      return -1
  },
  // 导师排序-end

  // 考号排序-begin
  orderByNumber: function (e) {
    console.log("根据考号排序")
    var arr = this.data.signUpList;
    this.setData({
      signUpList: arr.sort(this.compNumber)
    })
  },

  compNumber: function (a, b) {
    if (a.contestant_id >= b.contestant_id)
      return 1
    else
      return -1
  },
  // 考号排序-end
  // 排序-end

  // 点击通过报名成功
  setPass: function() {
    let that = this
    // console.log(that.data.batchIds.length)
    for (let i = 0; i < that.data.batchIds.length; ++i) {
      wx.cloud.callFunction({
        name: "updateSignUpState",
        data: {
          state: "成功",
          _id: that.data.batchIds[i],
        },
        success: res => {
          console.log("调用云函数通过报名成功", res)
          that.onReady()
        },
        fail: res => {
          console.log("调用云函数通过报名失败", res)
        }
      })
    }
  },

  // 点击排除报名失败
  setFail: function() {
    let that = this
    // console.log(that.data.batchIds.length)
    for (let i = 0; i < that.data.batchIds.length; ++i) {
      wx.cloud.callFunction({
        name: "updateSignUpState",
        data: {
          state: "失败",
          _id: that.data.batchIds[i],
        },
        success: res => {
          console.log("调用云函数筛选报名成功", res)
          that.onReady()
        },
        fail: res => {
          console.log("调用云函数筛选报名失败", res)
        }
      })
    }
  },

  // 点击导出导出报名表
  exportExcel: function () {
    let that = this
    // console.log(that.data.batchIds.length)
    wx.cloud.callFunction({
      name: "createExcel",
      data: {
        gameTitle: that.data.gameTitle,
        signUpList: that.data.signUpList,
      },
      success: res => {
        console.log("调用云函数生成excel成功", res)
        // 下载生成的excel
        wx.cloud.downloadFile({
          fileID: res.result.fileID,
          success: sres => {
            console.log("下载附件成功", sres.tempFilePath)
            // 保存2222222222222
            // wx.saveFile({
            //   tempFilePath: sres.tempFilePath,
            //   success(tres) {
            //     console.log('保存excel成功', tres)
            //     const savedFilePath = tres.savedFilePath
            //     // 打开
            //     wx.openDocument({
            //       filePath: tres.savedFilePath,
            //       success: fres => {
            //         console.log('打开excel成功', fres)
            //       },
            //       fail: fres => {
            //         console.log('打开excel失败', fres)
            //       },
            //     })
            //   },
            //   fail(tres) {
            //     console.log('保存excel失败', tres) // res.savedFilePath 为一个本地缓存文件路径
            //   }
            // })

            //保存下载的excel11111111111111111111111111111111111
            wx.getFileSystemManager().saveFile({
              tempFilePath: sres.tempFilePath, // 传入一个本地临时文件路径, http://tmp/开头的
              filePath: wx.env.USER_DATA_PATH + "/" + that.data.gameTitle + '.xlsx', //保存到用户目录/abc文件中，此处文件名自定义，因为tempFilePath对应的是一大长串字符
              success(tres) {
                console.log('保存excel成功', tres) // res.savedFilePath 为一个本地缓存文件路径
                wx.showToast({
                  title: '文件已保存至：' + tres.savedFilePath,
                })
                //打开下载的excel
                wx.openDocument({
                  filePath: tres.savedFilePath,
                  showMenu: true,
                  success: fres => {
                    console.log('打开excel成功', fres)
                  },
                  fail: fres => {
                    console.log('打开excel失败', fres)
                  },
                })
              },
              fail(tres) {
                console.log('保存excel失败', tres) // res.savedFilePath 为一个本地缓存文件路径
              }
            })
          },
          fail: err => {
            // handle error
            console.log("下载附件失败", err)
          }
        })
      },
      fail: res => {
        console.log("调用云函数生成excel失败", res)
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取报名列表
    let that = this
    that.setData({
      gameId: options._id
    })
    // wx.cloud.callFunction({
    //   name: "getSignUpListByGameId",
    //   data: {
    //     gameId: options._id
    //   },
    //   success: res => {
    //     console.log("调用云函数获取报名列表成功", res)
    //     that.setData({
    //       signUpList: res.result.data
    //     })
    //   },
    //   fail: res => {
    //     console.log("调用云函数获取报名列表失败", res)
    //   }
    // })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let that = this
    wx.cloud.callFunction({
      name: "getSignUpListByGameIdAndState",
      data: {
        gameId: that.data.gameId,
        state: that.data.current_state
      },
      success: res => {
        console.log("调用云函数获取报名列表成功", res)
        that.setData({
          signUpList: res.result.data,
          batchIds: [],
          select_all: false,
        })
        // 获取比赛名称作为导出excel的名字
        if(that.data.signUpList.length > 0) {
          that.setData({
            gameTitle: that.data.signUpList[0].gameTitle
          })
        }
      },
      fail: res => {
        console.log("调用云函数获取报名列表失败", res)
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})